<template>
	<view class="user_wrap">
		<view class="status_bar">
		    <!-- 这里是状态栏 -->
		</view>
		<!-- 顶部蓝色渐变背景 -->
		<view class="top_bg">
			<view class="top_actions">
				<u-icon name="setting" @tap="toSetting" size="44" color="#fff"></u-icon>
				<u-icon name="chat" @tap="toMessage" size="44" color="#fff"></u-icon>
			</view>
		</view>
		
		<!-- 用户资料卡片 -->
		<view class="profile_card">
			<view class="profile_content">
				<!-- 左侧头像 -->
				<view class="avatar_section">
					<view class="avatar">
						<image :src="avatarUrl" mode="aspectFill"></image>
					</view>
				</view>
				
				<!-- 中间统计数据 -->
				<view class="stats_section">
					<view class="stat_item" @click="handleInfoClick({name: '关注'}, 0)">
						<text class="stat_number">{{followCount}}</text>
						<text class="stat_label">关注</text>
					</view>
					<view class="stat_item" @click="handleInfoClick({name: '粉丝'}, 1)">
						<text class="stat_number">{{fansCount}}</text>
						<text class="stat_label">粉丝</text>
					</view>
					<view class="stat_item" @click="handleInfoClick({name: '获赞'}, 2)">
						<text class="stat_number">{{formatLikes(likesCount)}}</text>
						<text class="stat_label">获赞</text>
					</view>
				</view>
			</view>
			
			<!-- 用户信息 -->
			<view class="user_info">
				<view class="username">{{randomName}}</view>
				<view class="user_tags">
					<view class="tag level_tag">Lv.{{userLevel}}</view>
					<view class="tag gender_tag" :class="{'male': userGender === 1, 'female': userGender === 2}" v-if="userGender !== 0">
						<text class="gender_symbol" v-if="userGender === 1">♂</text>
						<text class="gender_symbol" v-else-if="userGender === 2">♀</text>
						<text class="gender_text">{{genderText}}</text>
					</view>
				</view>
				<view class="homepage_link" @click="toHomepage">个人主页></view>
			</view>
		</view>
		
		<!-- 功能区域 -->
		<view class="info-box">
			<view class="icon_box">
				<view class="icon_item" v-for="(item,index) in info_list" :key="index" @click="handleInfoClick(item, index)">
					<text class="name">{{item.num}}</text>
					<text>{{item.name}}</text>
				</view>
			</view>
		</view>
		<view class="order-wrap">
			<view class="flex-between">
				<view class="title">我的订单</view>
				<view class="all">
					<text>全部订单</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
			</view>
			<view class="icon_box">
				<view class="icon_item" v-for="(item,index) in order_list" :key="index">
					<image :src="item.icon" mode=""></image>
					<text>{{item.name}}</text>
				</view>
			</view>
		</view>
		<view class="order-wrap">
			<view class="flex-between">
				<view class="title" >我的足迹</view>
				<view class="all" @tap="toStep">
					<text>全部足迹</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
			</view>
			<view class="btn-box">
				<u-button :custom-style="customStyle" :ripple="true" size="medium" type="warning" ripple-bg-color="rgba(0,0,0,.1)">
					<u-icon name="zhuanfa" size="40"></u-icon>
					<text class="ml20">分享你的足迹</text>
				</u-button>
			</view>
		</view>
		<view class="order-wrap">
			<view class="flex-between">
				<view class="title">更多服务</view>
				<view class="all">
					<text>更多</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
			</view>

			<view class="icon_box">
				<view class="icon_item" v-for="(item,index) in server_list" :key="index">
					<image :src="item.icon" mode=""></image>
					<text>{{item.name}}</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
import $api from '../../api/user.js';

export default {

	data(){
		return{
			title:'',
			avatarUrl: require('../../static/image/user/avatar.jpg'), // 固定头像
			randomName: '旅行者', // 随机名字
			userLevel: 0, // 用户等级
			userGender: 0, // 用户性别 0-未知，1-男，2-女
			followCount: 0, // 关注数
			fansCount: 0, // 粉丝数
			likesCount: 0, // 获赞数
			customStyle:{
				backgroundColor:'#FFCF31',
				height:'80rpx',
				borderRadius:'40rpx',
				color:'#223322'
			},
			info_list:[
				{
					name:'收藏',
					num:0,
					clickable: true
				},
				{
					name:'点评',
					num:0,
					clickable: true
				},
				{
					name:'优惠券',
					num:0,
					clickable: true
				},				{
					name:'游记',
					num:0,
					clickable: true
				}
			],
			order_list:[
				{
					icon:require('../../static/image/user/dfk.png'),
					name:'待付款'
				},
				{
					icon:require('../../static/image/user/dcx.png'),
					name:'待出行'
				},
				{
					icon:require('../../static/image/user/dpj.png'),
					name:'待点评'
				},
				{
					icon:require('../../static/image/user/ls.png'),
					name:'历史'
				},
			],
			server_list:[
				{
					icon:require('../../static/image/user/mall.png'),
					name:'积分商城'
				},
				{
					icon:require('../../static/image/user/wallet.png'),
					name:'钱包'
				},
				{
					icon:require('../../static/image/user/member.png'),
					name:'会员卡'
				},
			]
		}
	},
	created() {
		// 监听收藏数量变化事件
		uni.$on('favoriteCountChanged', () => {
			this.loadFavoriteCount();
		});
		// 监听统计数据同步事件
		uni.$on('statsDataChanged', (data) => {
			if (data.followCount !== undefined) {
				this.followCount = data.followCount;
			}
			if (data.fansCount !== undefined) {
				this.fansCount = data.fansCount;
			}
			if (data.likesCount !== undefined) {
				this.likesCount = data.likesCount;
			}
		});
		// 监听用户信息更新事件
		uni.$on('userInfoChanged', (data) => {
			if (data.gender !== undefined) {
				this.userGender = data.gender;
			}
			if (data.avatar !== undefined && data.avatar) {
				this.avatarUrl = data.avatar;
			}
			if (data.level !== undefined) {
				this.userLevel = data.level || 0;
			}
			// 如果昵称变化，重新生成随机名字
			if (data.nickname !== undefined) {
				this.generateRandomName();
			}
		});
	},
	mounted() {
		// 页面加载时生成随机名字
		this.generateRandomName();
		// 加载用户信息
		this.loadUserInfo();
		// 加载收藏数量
		this.loadFavoriteCount();
		// 加载点评数量
		this.loadCommentCount();
		// 加载优惠券数量
		this.loadCouponCount();
		// 加载游记数量
		this.loadArticleCount();
	},
	onShow() {
		// 页面显示时刷新收藏数量
		this.loadFavoriteCount();
		// 刷新点评数量
		this.loadCommentCount();
		// 刷新优惠券数量
		this.loadCouponCount();
		// 刷新游记数量
		this.loadArticleCount();
		// 从本地存储同步统计数据
		this.loadStatsFromStorage();
		// 从本地存储同步用户信息（性别、头像、等级等）
		this.loadUserInfo();
	},
	beforeDestroy() {
		// 移除事件监听
		uni.$off('favoriteCountChanged');
		uni.$off('statsDataChanged');
		uni.$off('userInfoChanged');
	},
	computed: {
		// 获取性别文本
		genderText() {
			if (this.userGender === 1) {
				return '男';
			} else if (this.userGender === 2) {
				return '女';
			}
			return '未知';
		}
	},
	methods:{
		// 生成随机名字（基于用户名或手机号，确保同一用户每次显示相同名字）
		generateRandomName() {
			try {
				// 获取用户信息
				const user = uni.getStorageSync('user');
				
				// 如果用户有昵称，优先使用昵称
				if (user && user.nickname && user.nickname.trim()) {
					this.randomName = user.nickname;
					return;
				}
				
				// 获取用户名或手机号作为唯一标识
				let userIdentifier = '';
				if (user) {
					// 优先使用手机号
					if (user.phone && user.phone.trim()) {
						userIdentifier = user.phone;
					} 
					// 如果没有手机号，使用用户名
					else if (user.username && user.username.trim()) {
						userIdentifier = user.username;
					}
				}
				
				// 如果都没有，尝试从token中提取
				if (!userIdentifier) {
					const token = uni.getStorageSync('token') || '';
					userIdentifier = token;
				}
				
				// 如果还是没有，使用默认值
				if (!userIdentifier) {
					this.randomName = '旅行者';
					return;
				}
				
				// 随机名字列表（35个不同的名字）
				const nameList = [
					'旅行者', '探索者', '冒险家', '漫游者', '行者', '游侠',
					'追风者', '逐梦人', '自由人', '背包客', '旅人', '过客',
					'风景猎人', '城市漫步者', '山川行者', '海岸追光者', '星空守望者',
					'云游四方', '踏遍山河', '寻梦之旅', '心之所向', '诗和远方',
					'风一样的', '雨中的', '阳光下的', '月光里的', '晨曦中的',
					'小旅行家', '大冒险家', '新探索者', '老游侠', '资深旅人',
					'梦想家', '追光者', '拾光者', '时光旅人', '远方来客'
				];
				
				// 基于用户名或手机号生成哈希值，确保同一用户每次显示相同名字
				const hashValue = Math.abs(this.hashCode(userIdentifier));
				const nameIndex = hashValue % nameList.length;
				this.randomName = nameList[nameIndex];
				
			} catch (e) {
				console.error('生成随机名字失败', e);
				this.randomName = '旅行者';
			}
		},
		// 字符串哈希函数（用于生成数字ID）
		hashCode(str) {
			let hash = 0;
			if (str.length === 0) return hash;
			for (let i = 0; i < str.length; i++) {
				const char = str.charCodeAt(i);
				hash = ((hash << 5) - hash) + char;
				hash = hash & hash; // Convert to 32bit integer
			}
			return hash;
		},
		toSetting(){
			uni.navigateTo({
				url:'./setting'
			})
		},
		toMessage(){
			uni.switchTab({
				url:"../msg/msg"
			})
		},
		toStep(){
			uni.navigateTo({
				url:'./step'
			})
		},
		// 处理信息项点击
		handleInfoClick(item, index) {
			if (item.name === '收藏' && item.clickable) {
				uni.navigateTo({
					url: './favorite'
				});
			} else if (item.name === '点评') {
				uni.navigateTo({
					url: './comment'
				});
			} else if (item.name === '优惠券') {
				uni.navigateTo({
					url: './coupon'
				});
			} else if (item.name === '游记') {
				uni.navigateTo({
					url: './article'
				});
			} else if (item.name === '关注') {
				// 跳转到关注列表
				uni.showToast({
					title: '关注功能开发中',
					icon: 'none'
				});
			} else if (item.name === '粉丝') {
				// 跳转到粉丝列表
				uni.showToast({
					title: '粉丝功能开发中',
					icon: 'none'
				});
			} else if (item.name === '获赞') {
				// 跳转到获赞列表
				uni.showToast({
					title: '获赞功能开发中',
					icon: 'none'
				});
			}
		},
		// 加载用户信息
		loadUserInfo() {
			const user = uni.getStorageSync('user');
			if (user) {
				this.userLevel = user.level || 0;
				this.userGender = user.gender !== undefined ? user.gender : 0;
				if (user.avatar) {
					this.avatarUrl = user.avatar;
				}
			}
			// 从本地存储加载统计数据
			this.loadStatsFromStorage();
		},
		// 从本地存储加载统计数据
		loadStatsFromStorage() {
			const stats = uni.getStorageSync('user_stats');
			if (stats) {
				if (stats.followCount !== undefined) {
					this.followCount = stats.followCount;
				}
				if (stats.fansCount !== undefined) {
					this.fansCount = stats.fansCount;
				}
				if (stats.likesCount !== undefined) {
					this.likesCount = stats.likesCount;
				}
			}
		},
		// 保存统计数据到本地存储
		saveStatsToStorage() {
			uni.setStorageSync('user_stats', {
				followCount: this.followCount,
				fansCount: this.fansCount,
				likesCount: this.likesCount
			});
			// 发送同步事件
			uni.$emit('statsDataChanged', {
				followCount: this.followCount,
				fansCount: this.fansCount,
				likesCount: this.likesCount
			});
		},
		// 格式化获赞数
		formatLikes(count) {
			if (count < 10000) {
				return count.toString();
			} else if (count < 100000000) {
				return (count / 10000).toFixed(1) + '万';
			} else {
				return (count / 100000000).toFixed(1) + '亿';
			}
		},
		// 跳转到个人主页
		toHomepage() {
			uni.navigateTo({
				url: './homepage'
			});
		},
		// 加载收藏数量
		loadFavoriteCount() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				return;
			}
			
			$api.getFavoriteCount({
				userId: user.id
			}).then(res => {
				if (res.data && res.data.code === 200) {
					const count = res.data.data || 0;
					// 更新收藏数量
					const favoriteItem = this.info_list.find(item => item.name === '收藏');
					if (favoriteItem) {
						favoriteItem.num = count;
					}
				}
			}).catch(err => {
				console.error('获取收藏数量失败', err);
			});
		},
		// 加载点评数量
		loadCommentCount() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				return;
			}
			
			$api.getCommentCount({
				userId: user.id
			}).then(res => {
				if (res.data && res.data.code === 200) {
					const count = res.data.data || 0;
					// 更新点评数量
					const commentItem = this.info_list.find(item => item.name === '点评');
					if (commentItem) {
						commentItem.num = count;
					}
				}
			}).catch(err => {
				console.error('获取点评数量失败', err);
			});
		},
		// 加载优惠券数量
		loadCouponCount() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				return;
			}
			
			$api.getCouponCount({
				userId: user.id
			}).then(res => {
				if (res.data && res.data.code === 200) {
					const count = res.data.data || 0;
					// 更新优惠券数量
					const couponItem = this.info_list.find(item => item.name === '优惠券');
					if (couponItem) {
						couponItem.num = count;
					}
				}
			}).catch(err => {
				console.error('获取优惠券数量失败', err);
			});
		},
	},
}
</script>
<style lang="scss" scoped>
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}
page{
	font-family: '-apple-system', 'BlinkMacSystemFont', 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.ml20{
	margin-left: 20rpx;
}
.user_wrap{
	box-sizing: border-box;
	background-color: #FAFAFA;
	// height: 100vh;
	padding-bottom: 40rpx;
	width: 100vw;
	.btn-box{
		display: flex;
		justify-content: center;
		align-items: center;
		height: 140rpx;
	}
	.info-box{
		width: 90%;
		position: relative;
		z-index: 10;
		background-color: #fff;
		box-shadow: 0 0 10px 2px rgba(0,0,0,.1);
		border-radius: 10rpx;
		margin: 0 auto;
		margin-top: 30rpx;
		.icon_box{
			display: flex;
			width: 100%;
			justify-content: space-around;
			align-items: center;
			font-size: 30rpx;
			color:#333;
			.icon_item{
				height: 90rpx;
				margin-top: 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				.name{
					font-weight: bold;
				}
			}
		}
	}
	.order-wrap{
		width: 90%;
		position: relative;
		z-index: 10;
		// height: 200rpx;
		background-color: #fff;
		box-shadow: 0 0 10px 2px rgba(0,0,0,.1);
		border-radius: 10rpx;
		margin: 0 auto;
		margin-top: 40rpx;
		.flex-between{
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-sizing: border-box;
			padding:20rpx 20rpx 0;
		}
		.title{
			font-size: 32rpx;
			font-weight: bold;
		}
		.all{
			font-size: 26rpx;
			color:#999;
		}
		.icon_box{
			display: flex;
			// justify-content: space-between;
			align-items: center;
			box-sizing: border-box;
			padding:20rpx;
			.icon_item{
				width: 25%;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				image{
					width: 60rpx;
					height: 60rpx;
				}
				text{
					font-size: 26rpx;
				}
			}
			
		}
	}
	.slot-wrap{
		flex:1;
		display: flex;
		justify-content: flex-end;
		box-sizing: border-box;
		padding-right: 20rpx;
		image{
			width: 44rpx;
			height: 44rpx;
		}
	}
	.top_bg {
		width: 100%;
		height: 280rpx;
		background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
		position: relative;
		
		.top_actions {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			padding-top: calc(var(--status-bar-height) + 20rpx);
		}
	}
	
	.profile_card {
		width: 90%;
		margin: 0 auto;
		margin-top: -120rpx;
		background-color: #fff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		padding: 40rpx 30rpx;
		position: relative;
		z-index: 10;
		
		.profile_content {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			
			.avatar_section {
				margin-right: 30rpx;
				
				.avatar {
					width: 140rpx;
					height: 140rpx;
					border-radius: 50%;
					overflow: hidden;
					background-color: #f5f5f5;
					border: 4rpx solid #fff;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
					
					image {
						width: 100%;
						height: 100%;
					}
				}
			}
			
			.stats_section {
				flex: 1;
				display: flex;
				justify-content: space-around;
				
				.stat_item {
					display: flex;
					flex-direction: column;
					align-items: center;
					
					.stat_number {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 8rpx;
					}
					
					.stat_label {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
		
		.user_info {
			.username {
				font-size: 40rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.user_tags {
				display: flex;
				align-items: center;
				gap: 16rpx;
				margin-bottom: 20rpx;
				
				.tag {
					padding: 8rpx 20rpx;
					border-radius: 30rpx;
					font-size: 24rpx;
					
					&.level_tag {
						background-color: #FF9500;
						color: #fff;
					}
					
					&.gender_tag {
						border-radius: 50rpx;
						padding: 8rpx 20rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						
						&.male {
							background-color: #E5F3FF;
							color: #4A90E2;
							border: 1rpx solid #4A90E2;
						}
						
						&.female {
							background-color: #FFE5E5;
							color: #FF6B6B;
							border: 1rpx solid #FF6B6B;
						}
						
						.gender_symbol {
							margin-right: 8rpx;
							font-weight: bold;
							font-size: 28rpx;
							line-height: 1;
						}
						
						.gender_text {
							font-size: 24rpx;
							line-height: 1;
						}
					}
				}
			}
			
			.homepage_link {
				text-align: right;
				font-size: 26rpx;
				color: #4A90E2;
				margin-top: 10rpx;
			}
		}
	}
}
</style>